import styles from './index.less';
import './position.less';
import ScaleContainer from '@/components/ScaleContainer/index';
import {
  _getObjBoxFishpondDevices,
  _getObjBoxInfo,
  _openOrCloseSwitch,
} from '@/api/sysUser';
import {
  _getVideoCondition,
  _getDataDeviceAlarmList,
  _getDataScheduleTaskAlarmList,
  _getDataBoxPushAlarmList,
} from '@/api/baseCondition';

import { useEffect, useState, useRef } from 'react';
import { getUserInfo, isFullscreen } from '@/utils';
import { Modal, message, Button } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
const { confirm } = Modal;
import { history } from 'umi';
import Select from '../Home/components/Select';
import VideoM3u8V from './components/VideoM3u8V';

export default function IndexPage() {
  const refEle = useRef(null);
  const [goinObj, setGoinObj] = useState<any>({}); //进水控制箱
  const [putOutObj, setPutOutObj] = useState<any>({}); //尾水控制箱
  const [fishArry, setFishArry] = useState<any>([]); //鱼池
  const [isDlog, setIsDlog] = useState<boolean>(false); //信息框
  const [dlogObj, setDlogObj] = useState<any>([]); //信息框对象
  const [dlogName, setDlogName] = useState<string>(''); //信息框对象
  const [zyj, setZyj] = useState<any>({}); //信息框增氧机对象
  const [isClog, setIsClog] = useState<boolean>(false); //确定框
  const [clogObj, setClogObj] = useState<any>({}); //确定框对象
  const [videoCondition, setVideoCondition] = useState<any>([]); //全部摄像头
  const [playObj, setPlayObj] = useState<any>({}); //当前摄像头
  const [isVideo, setIsVideo] = useState<boolean>(false); //视频框
  const [alarmList, setAlarmList] = useState<any>([]); //告警
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false); //告警框
  const getObjBoxInfo = () => {
    _getObjBoxInfo({ id: 13 }).then((res) => {
      if (res.code == 200) {
        setGoinObj(res.data);
      }
    });
    _getObjBoxInfo({ id: 14 }).then((res) => {
      if (res.code == 200) {
        setPutOutObj(res.data);
      }
    });
  };
  const getObjBoxFishpondDevices = () => {
    const rightIcon = [
      '12-s17',
      '11-s17',
      '10-s17',
      '9-s17',
      '8-s16',
      '8-s17',
      '7-s16',
      '7-s17',
      '5-s17',
    ];
    _getObjBoxFishpondDevices({
      baseId: history.location.query?.baseId || 1,
      companyId: history.location.query?.companyId || 1,
    }).then((res) => {
      if (res.code == 200) {
        const newItems = res.data.map((item: any) => {
          const nItems = item.valveList.map((i: any) => {
            const str = `${item.id}-${i.attributeCode}`;
            return {
              ...i,
              left: rightIcon.includes(str),
            };
          });
          return {
            ...item,
            valveList: nItems,
          };
        });
        setFishArry(newItems);
      }
    });
  };
  const openOrCloseSwitch = () => {
    let item = clogObj;
    _openOrCloseSwitch({
      attributeCode: item.attributeCode,
      deviceCode: item.deviceCode,
      status: item.deviceStatus == 1 ? 0 : 1,
      type: 0,
    }).then((res) => {
      if (res.code == 200) {
        getObjBoxFishpondDevices();
        getObjBoxInfo();
        setClogObj({});
        setIsClog(false);
        message.success(res.msg);
      }
    });
  };
  /**
   * 获取全部摄像头
   */
  const getVideoCondition = async () => {
    const res = await _getVideoCondition({
      baseId: history.location.query?.baseId || 1,
      companyId: history.location.query?.companyId || 1,
    });
    if (res.code === 200) {
      let newData = res.data?.map((item: any) => {
        return {
          ...item,
          value: item.id,
          label: item.name,
        };
      });
      setPlayObj(newData[0]?.id ? newData[0] : {});
      setVideoCondition(newData);
    }
  };
  const getDataDeviceAlarmList = async () => {
    const res = await _getDataDeviceAlarmList({
      baseId: history.location.query?.baseId || 1,
      companyId: history.location.query?.companyId || 1,
    });
    const res1 = await _getDataScheduleTaskAlarmList({
      baseId: history.location.query?.baseId || 1,
      companyId: history.location.query?.companyId || 1,
      type: 0,
    });
    const res2 = await _getDataScheduleTaskAlarmList({
      baseId: history.location.query?.baseId || 1,
      companyId: history.location.query?.companyId || 1,
      type: 0,
    });
    const res3 = await _getDataBoxPushAlarmList({
      baseId: history.location.query?.baseId || 1,
      companyId: history.location.query?.companyId || 1,
    });
    if (res.code === 200) {
      let alarmArry = [];
      if (res.data?.data?.length > 0 && res.data?.data[0]?.endDate == null) {
        alarmArry.push(res.data.data[0]);
      }
      if (res1.data?.data?.length > 0 && res1.data?.data[0]?.endDate == null) {
        alarmArry.push(res1.data.data[0]);
      }
      if (res2.data?.data?.length > 0 && res2.data?.data[0]?.endDate == null) {
        alarmArry.push(res2.data.data[0]);
      }
      if (res3.data?.data?.length > 0 && res3.data?.data[0]?.endDate == null) {
        alarmArry.push(res3.data.data[0]);
      }
      let a: any = [];
      let sureAlarmList: any = JSON.parse(
        sessionStorage.getItem('sureAlarmList') || '[]',
      );
      alarmArry.forEach((item: any) => {
        let isNOt: any = true;
        sureAlarmList.forEach((itema: any) => {
          if (item.id == itema.id && item.startDate == itema.startDate) {
            isNOt = false;
          }
        });
        if (isNOt) {
          a.push(item);
        }
      });
      if (a.length > 0) {
        setIsModalOpen(true);
      } else {
        setIsModalOpen(false);
      }
      setAlarmList(a);
    }
  };
  useEffect(() => {
    sessionStorage.setItem('sureAlarmList', '[]');
    getDataDeviceAlarmList();
    getObjBoxInfo();
    getObjBoxFishpondDevices();
    getVideoCondition();
    let timer: any = setInterval(() => {
      getObjBoxFishpondDevices();
      getDataDeviceAlarmList();
    }, 6000);
    return () => {
      clearInterval(timer);
      timer = null;
    };
  }, []);
  useEffect(() => {
    if (!isFullscreen()) {
      confirm({
        title: '全屏',
        icon: <ExclamationCircleFilled />,
        content: '全屏效果更好哦，是否全屏',
        cancelText: '取消',
        okText: '确定',
        onOk() {
          let ele: any = document.body;
          if (ele.requestFullscreen) {
            ele.requestFullscreen();
          } else if (ele.mozRequestFullScreen) {
            ele.mozRequestFullScreen();
          } else if (ele.webkitRequestFullscreen) {
            ele.webkitRequestFullscreen();
          } else if (ele.msRequestFullscreen) {
            ele.msRequestFullscreen();
          }
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }
  }, []);
  return (
    <div className={styles.page}>
      <ScaleContainer width={1920} height={1080}>
        <div>
          <img
            className={styles.bgImg}
            src={require('@/assets/bg.jpg')}
            alt=""
          />
          <div>
            <p className={styles.kzx8}>SS8</p>
            <p className={styles.kzx7}>SS7</p>
            <p className={styles.kzx6}>SS6</p>
            <p className={styles.kzx5}>SS5</p>
            <p className={styles.kzx4}>SS4</p>
            <p className={styles.kzx3}>SS3</p>
            <p className={styles.kzx2}>SS2</p>
            <p className={styles.kzx1}>SS1</p>
            {fishArry?.map((item: any) => (
              <div className={`kzxList kzxList${item.id}`} key={item.id}>
                <img
                  onClick={() => {
                    setIsDlog(true);
                    setIsClog(false);
                    setClogObj({});
                    setDlogObj(item.devices);
                    setDlogName(`${item.name}状态`);
                    setZyj({});
                  }}
                  style={{ width: '34px', height: '47px' }}
                  className="greenBox"
                  src={
                    item.deviceStatus == '1'
                      ? require('@/assets/greenBox.png')
                      : require('@/assets/greenBox2.png')
                  }
                  alt=""
                />
                <div className="valveListBox">
                  {item.valveList?.map((ite: any) => (
                    <div key={ite.attributeCode}>
                      <div
                        onClick={() => {
                          setClogObj(ite);
                          setIsClog(true);
                        }}
                        className={`valveListBoxItem valveListBoxItem${item.id}${ite.attributeCode}`}
                      >
                        {!ite.left && ite.deviceStatus == 1 ? (
                          <img
                            className={styles.kgimgs}
                            src={require('@/assets/l1.png')}
                            alt=""
                          />
                        ) : null}
                        {!ite.left &&
                        (ite.deviceStatus == 0 || ite.deviceStatus == 2) ? (
                          <img
                            className={styles.kgimgs}
                            src={require('@/assets/l2.png')}
                            alt=""
                          />
                        ) : null}
                        {!ite.left && ite.deviceStatus == 3 ? (
                          <img
                            className={styles.kgimgs}
                            src={require('@/assets/l3.png')}
                            alt=""
                          />
                        ) : null}
                        {ite.left && ite.deviceStatus == 1 ? (
                          <img
                            className={styles.kgimgs}
                            src={require('@/assets/r1.png')}
                            alt=""
                          />
                        ) : null}
                        {ite.left &&
                        (ite.deviceStatus == 0 || ite.deviceStatus == 2) ? (
                          <img
                            className={styles.kgimgs}
                            src={require('@/assets/r2.png')}
                            alt=""
                          />
                        ) : null}
                        {ite.left && ite.deviceStatus == 3 ? (
                          <img
                            className={styles.kgimgs}
                            src={require('@/assets/r3.png')}
                            alt=""
                          />
                        ) : null}
                      </div>
                      {ite.fishpondList?.map((it: any) => (
                        <div
                          key={it.fishpondName}
                          className={`fishpondListItem fishpondListItem${it.fishpondName}`}
                        >
                          <img
                            onClick={() => {
                              setIsDlog(true);
                              setDlogObj(it.numericalList);
                              setDlogName(`${it.fishpondName}数据`);
                              setZyj(it.switchList[0] || {});
                              setIsClog(false);
                              setClogObj({});
                            }}
                            className={styles.fishC}
                            src={
                              it.status == 1
                                ? require('@/assets/yuchiB.png')
                                : require('@/assets/yuchiA.png')
                            }
                            alt=""
                          />
                          <div className="fishpondName">
                            {it.switchList[0].deviceStatus == 1 ? (
                              <img
                                className="fishpondNameImg"
                                src={require('@/assets/yc.gif')}
                                alt=""
                              />
                            ) : (
                              <img
                                className="fishpondNameImg"
                                src={require('@/assets/zyj.png')}
                                alt=""
                              />
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  ))}
                </div>
              </div>
            ))}
            {/* 尾水控制箱 */}
            <div className={styles.outs}>
              <img
                onClick={() => {
                  setIsDlog(true);
                  setDlogObj(putOutObj.boxNumericals);
                  setDlogName(`尾水控制区`);
                  setZyj({});
                  setIsClog(false);
                  setClogObj({});
                }}
                src={
                  putOutObj.deviceStatus == '1'
                    ? require('@/assets/greenBox.png')
                    : require('@/assets/greenBox2.png')
                }
                alt=""
              />
              <h3>尾水控制区</h3>
            </div>
            {/* 进水控制箱 */}
            <div className={styles.ins}>
              <img
                onClick={() => {
                  setIsDlog(true);
                  setDlogObj(goinObj.boxNumericals);
                  setDlogName(`进水控制区`);
                  setZyj({});
                  setIsClog(false);
                  setClogObj({});
                }}
                src={
                  goinObj?.deviceStatus == '1'
                    ? require('@/assets/greenBox.png')
                    : require('@/assets/greenBox2.png')
                }
                alt=""
              />
              <h3>进水控制区</h3>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[0]);
                setIsVideo(true);
              }}
              className={styles.sxt0}
            >
              <div className={styles.sxtv}>1</div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[2]);
                setIsVideo(true);
              }}
              className={styles.sxt1}
            >
              <div className={styles.sxtv}>2</div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[9]);
                setIsVideo(true);
              }}
              className={styles.sxt2}
            >
              <div className={styles.sxtv}></div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[8]);
                setIsVideo(true);
              }}
              className={styles.sxt3}
            >
              <div className={styles.sxtv}></div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[7]);
                setIsVideo(true);
              }}
              className={styles.sxt4}
            >
              <div className={styles.sxtv}></div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[4]);
                setIsVideo(true);
              }}
              className={styles.sxt5}
            >
              <div className={styles.sxtv}></div>
            </div>
            <div
              onClick={() => {
                setPlayObj(videoCondition[6]);
                setIsVideo(true);
              }}
              className={styles.sxt6}
            >
              <div className={styles.sxtv}></div>
            </div>
            {isDlog ? (
              <div
                className={`${styles.ddlog} ${
                  dlogObj?.length > 14 ? styles.ddlog2 : ''
                }`}
              >
                <h4>{dlogName}</h4>
                {zyj?.attributeCode ? (
                  <div className={styles.listv}>
                    <div className={styles.listvL}>{zyj?.deviceName}：</div>
                    <div
                      className={styles.listvR}
                      onClick={() => {
                        setClogObj(zyj || {});
                        setIsClog(true);
                      }}
                    >
                      {zyj?.deviceStatus == 1 ? (
                        <img
                          className="zyjImg"
                          src={require('@/assets/on.jpg')}
                          alt=""
                        />
                      ) : (
                        <img
                          className="zyjImg"
                          src={require('@/assets/off.jpg')}
                          alt=""
                        />
                      )}
                    </div>
                  </div>
                ) : null}
                <div
                  className={`${dlogObj?.length > 14 ? styles.ddlogBox : ''}`}
                >
                  {dlogObj?.map((item: any) => (
                    <div className={styles.listv} key={item.id}>
                      <span className={styles.listvL}>{item.deviceName}：</span>
                      <span className={styles.listvR}>
                        {item.realDataConvert}
                        {item.unit}
                      </span>
                    </div>
                  ))}
                </div>
                <img
                  className={styles.closeImg}
                  onClick={() => {
                    setIsDlog(false);
                    setDlogObj([]);
                    setDlogName(``);
                  }}
                  src={require('@/assets/close.png')}
                  alt=""
                />
              </div>
            ) : null}
            {isClog ? (
              <div className={styles.dlog}>
                <h4>提示</h4>
                <p>
                  是否{clogObj.deviceStatus == 1 ? '关闭' : '开启'}
                  {clogObj.deviceName}
                </p>
                <div className={styles.btns}>
                  <div
                    onClick={() => {
                      setClogObj({});
                      setIsClog(false);
                    }}
                    className={styles.btn}
                  >
                    取消
                  </div>
                  <div
                    onClick={() => {
                      openOrCloseSwitch();
                    }}
                    className={styles.btn}
                  >
                    确定
                  </div>
                </div>
              </div>
            ) : null}
            {isVideo ? (
              <div className={styles.videoBox}>
                <div className={styles.videoTitles}>
                  <div className={styles.videoTitle}>视频监控</div>
                  <div className={styles.select}>
                    <Select
                      widthName={300}
                      onChange={(e: any) => {
                        setPlayObj(e);
                      }}
                      ac={playObj ? playObj : videoCondition[0]}
                      op={videoCondition}
                    />
                  </div>
                </div>
                <div className={styles.videobox}>
                  <VideoM3u8V playObj={playObj} />
                </div>
                <img
                  className={styles.closeImg}
                  onClick={() => {
                    setIsVideo(false);
                  }}
                  src={require('@/assets/close.png')}
                  alt=""
                />
              </div>
            ) : null}
            {alarmList.length > 0 ? (
              <Modal
                width={420}
                wrapClassName={'alarmBoxa'}
                footer={
                  <Button
                    onClick={() => {
                      setIsModalOpen(false);
                      let a: any = JSON.parse(
                        sessionStorage.getItem('sureAlarmList') || '[]',
                      );
                      a.push(alarmList[0]);
                      sessionStorage.setItem(
                        'sureAlarmList',
                        JSON.stringify(a),
                      );
                      setTimeout(function () {
                        let sureAlarmList: any = JSON.parse(
                          sessionStorage.getItem('sureAlarmList') || '[]',
                        );
                        if (sureAlarmList.length > 0) {
                          var newArr: any = sureAlarmList.slice(1);
                          sessionStorage.setItem(
                            'sureAlarmList',
                            JSON.stringify(newArr),
                          );
                        }
                      }, 180000);
                    }}
                    type="primary"
                  >
                    确定
                  </Button>
                }
                title="报警提醒"
                open={isModalOpen}
                onCancel={() => {
                  setIsModalOpen(false);
                  let a: any = JSON.parse(
                    sessionStorage.getItem('sureAlarmList') || '[]',
                  );
                  a.push(alarmList[0]);
                  sessionStorage.setItem('sureAlarmList', JSON.stringify(a));
                  setTimeout(function () {
                    let sureAlarmList: any = JSON.parse(
                      sessionStorage.getItem('sureAlarmList') || '[]',
                    );
                    if (sureAlarmList.length > 0) {
                      var newArr: any = sureAlarmList.slice(1);
                      sessionStorage.setItem(
                        'sureAlarmList',
                        JSON.stringify(newArr),
                      );
                    }
                  }, 180000);
                }}
                okText="确定"
                cancelText={null}
              >
                <div className={styles.alarmBox}>
                  <img
                    className={styles.alarmImg}
                    src={require('@/assets/alrm.png')}
                    alt=""
                  />
                  <h3 className={styles.alarmText}>
                    {alarmList[0].fishpondName
                      ? alarmList[0].fishpondName + '鱼池'
                      : alarmList[0].deviceName}
                    {alarmList[0].alarmType}
                  </h3>
                </div>
              </Modal>
            ) : null}
          </div>
        </div>
      </ScaleContainer>
    </div>
  );
}
